import axios from "axios";
import { useUserStore } from "@/store/user";
// import { getToken } from "@/utils/auth";
import router from "@/router";
declare const window: Window & { $message: any; $loadingBar: any };
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API as string, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20 * 1000, // request timeout
});
// request interceptor
service.interceptors.request.use(
  (config: any) => {
    // do something before request is sent
    // const store = useUserStore();
    // if (store.$state.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers.Authorization = getToken();
    // }

    // get 请求
    if(config.method.toLocaleUpperCase() === 'GET' && config.data) {
      config.params = config.data;
      delete config.data;
    }

    


    return config;
  },
  (error: any) => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response: any) => {
    const res = response.data;

    // Blob 类型
    if (res instanceof Blob) {
      return Promise.resolve(res);
    }

    // 登录-二维码失效
    if (res.code === 202) {
      return Promise.reject(res);
    }

    // 登录-未扫码
    if (res.code === 203) {
      return Promise.reject(new Error(res.msg || "Error"));
    }

    // 登录-已扫码 未绑定账户
    if (res.code === 204) {
      return Promise.reject(res);
    }

    // if the custom code is not 20000, it is judged as an error.
    // if (res.code === 401) {
      // const store = useUserStore();
      // store.logout();
    //   return Promise.reject(new Error(res.msg || "Error"));
    // }

    // if (res.code !== 200) {
    //   window.$message.error(res.msg || "Error");
    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   new Error(res.msg || "Error");
    //   return Promise.reject(res);
    // }
    return res;
  },
  (error: any) => {
    if (error.response) {
      const err = error.response.data;
      window.$message.error(err.msg || "Error");
      // if (err.code === 401) {
      //   const store = useUserStore();
      //   store.logout();
      // }
    } else if (error.request) {
      if (error.request.readyState == 4 && error.request.status == 0) {
        window.$message.error("请求超时");
      }
    }

    return Promise.reject(error);
  }
);

export default service;
